package com.ruoyi.service;

import com.google.protobuf.InvalidProtocolBufferException;
import com.ruoyi.domain.DeviceReport;
import com.ruoyi.protobuf.Om0Command;
import com.ruoyi.utils.MyDateTimeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class OldManDataParser implements IDataParser {
    private static final Logger log = LoggerFactory.getLogger(OldManDataParser.class);
@Autowired
private SaveInfoToRedisService saveInfoToRedisService;
    @Override
    public void DataParse(byte[] payload,String deviceId) {
        Om0Command.OM0Report report = null;
        try {
            report = Om0Command.OM0Report.parseFrom(payload);
        } catch (InvalidProtocolBufferException ex) {
            ex.printStackTrace();
            return;
        }

        //data time
        int seconds = report.getDateTime().getDateTime().getSeconds();
        String data_time = MyDateTimeUtils.convert2DateTimeString(seconds);

        //realtime step/distance/calorie
        float distance = report.getHealth().getDistance()*0.1F;
        float calorie = report.getHealth().getCalorie()*0.1F;
        log.info(String.format("%s steps:%d, distance:%f, calorie:%f",data_time,report.getHealth().getSteps(),distance,calorie));

        //device batterylevel/rssi
        log.info(String.format("%s battery:%d, rssi:%d",data_time,report.getBattery().getLevel(),report.getRssi()));
        DeviceReport reportObj = new DeviceReport();
        reportObj.setStep(report.getHealth().getSteps());
        reportObj.setBattery(report.getBattery().getLevel());
        reportObj.setDateTime(data_time);
        reportObj.setRssi(report.getRssi());
        reportObj.setDistance(distance);
        reportObj.setCalorie(calorie);
        reportObj.setSn(deviceId);
        saveInfoToRedisService.saveDeviceReportToRedis(deviceId, reportObj);
        //gnss location
        //*notice: the location upload by device is in WGS_84 coordinate system, not GCJ_02
        List<Om0Command.OM0TrackData> gnssList = report.getTrackDataList();
        if(gnssList != null){
            for(int i=0;i<gnssList.size();i++){
                Om0Command.OM0TrackData gnss = gnssList.get(i);
                String gnss_date = MyDateTimeUtils.convert2DateTimeString(gnss.getTime().getDateTime().getSeconds());
                log.info(String.format("time:%s, lon:%f, lat:%f, loc_type:%d",
                        gnss_date,gnss.getGnss().getLongitude(),
                        gnss.getGnss().getLatitude(),
                        gnss.getGpsType().ordinal()));
            }
        }
    }
}
